package ru.pb.global.compiler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;

import org.apache.log4j.Logger;
import org.eclipse.jdt.internal.compiler.tool.EclipseCompiler;

;

public class MainCompiler
{
	private static final Logger _log = Logger.getLogger(MainCompiler.class);
	private static MainCompiler _instance;

	private final JavaCompiler _javac = new EclipseCompiler();
	private final DiagnosticListener<JavaFileObject> _diacol = new DiagnosticListenerImpl();
	private final StandardJavaFileManager _fileManager = _javac.getStandardFileManager(_diacol, null, null);

	private MemoryClassLoader _classLoader;

	public static MainCompiler getInstance()
	{
		if(_instance == null)
		{
			_instance = new MainCompiler();
		}

		return _instance;
	}

	public boolean compile(List<File> fg)
	{
		return compile(fg.toArray(new File[fg.size()]));
	}

	public boolean compile(File... files)
	{
		List<String> options = new ArrayList<String>();
		options.add("-Xlint:all");
		options.add("-warn:none");
		options.add("-g");

		_classLoader = new MemoryClassLoader();

		JavaMemoryFileManager fileManager = new JavaMemoryFileManager(_fileManager, _classLoader);

		JavaCompiler.CompilationTask task = _javac.getTask(null, fileManager, _diacol, options, null, _fileManager.getJavaFileObjects(files));

		return task.call();
	}

	public MemoryClassLoader getClassLoader()
	{
		return _classLoader;
	}

	public void free()
	{
		// _classLoader.free();
		_classLoader = null;
	}

	private class DiagnosticListenerImpl implements DiagnosticListener<JavaFileObject>
	{
		@Override
		public void report(Diagnostic<? extends JavaFileObject> diagnostic)
		{
			_log.info(diagnostic);
		}
	}
}
